<template>
	<view class="content">
		<!-- HTML -->
		<mumu-get-qrcode @success='qrcodeSucess' @error="qrcodeError"></mumu-get-qrcode>
	</view>
</template>

<script>
	import { getUInfo } from '@/util/util.js'
	import mumuGetQrcode from '@/uni_modules/mumu-getQrcode/components/mumu-getQrcode/mumu-getQrcode.vue'
	export default {
		components: {
			mumuGetQrcode
		},
		data() {
			return {
				myCp: {}, // 记录扫描出的优惠券对象
				qr_code_data: '', // 记录扫出来的二维码数据
			}
		},
		methods: {

			qrcodeSucess(data) {
				// 保存扫码数据
				// uni.setStorageSync('qr_code_data', data)
				// 通过事件总线发送数据

				// uni.navigateBack()
				// uni.$emit('onGetQrCode', { qr_code_data: data })

				// uni.showModal({
				// 	title: '二维码识别成功',
				// 	content: data,
				// 	success: res => {
				// 		uni.navigateBack({})
				// 	}
				// })

				let that = this
				that.myCp = JSON.parse(data)
				that.qr_code_data = that.myCp.coupon_code

				uni.showModal({
					title: '提示',
					content: `优惠券识别成功！面值:『¥${that.myCp.money}』有效期至:『${that.myCp.end_time_text}』。是否进行核销？`,
					success: res => {
						if (res.confirm) {
							that.reqHexiao()
						} else {
							uni.navigateBack()
						}
					}
				})

			},

			qrcodeError(err) {
				console.log(err)
				uni.showModal({
					title: '摄像头授权失败',
					content: '摄像头授权失败，请检测当前浏览器是否有摄像头权限。',
					success: res => {
						uni.navigateBack({})
					}
				})
			},

			// 接口:对优惠券进行核销
			async reqHexiao() {
				let that = this

				let token = getUInfo().token
				let coupon_code = that.qr_code_data
				uni.showLoading({ title: '处理中', mask: true, })
				let { code, msg, data } = await that.$hexiao({ token, coupon_code })
				// console.log(`reqHexiao...code=${code},msg=${msg},data=`, data)
				if (code == 1) {
					// 核销成功
					uni.showModal({
						title: '提示',
						content: '核销成功！',
						showCancel: false,
						success: res => {
							if (res.confirm) {
								uni.navigateBack()
							}
						}
					})
				} else {
					// uni.showToast({ title: msg, icon: 'none' })
					uni.showModal({
						title: '提示',
						content: `核销失败！${msg}`,
						showCancel: false,
						success: res => {
							if (res.confirm) {
								uni.navigateBack()
							}
						}
					})
					// uni.showToast({ title: `核销失败！${msg}`, icon: 'none' })
				}

			},

		}
	}
</script>

<style scoped>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
</style>